let async_hooks = require('async_hooks');
//创建异步全局变量
module.exports={
    async:init(),
    start,
}
//启动异步全局变量
function start(data){
    //创建异步全局常量池
    global.async.init();
    Object.keys(data).forEach(a =>async_global[a]=data[a]);
    let poolId=async_hooks.executionAsyncId();
    let DATA = {
        group:[poolId], status : false,
    }
    //保存临时文件
    let $file = [];
    async_global.$data=DATA;
    async_global.$file=$file;
    let number = 1;
    //bool标识着这一次的接口访问完整结束
    //监控异步的生成
    async_hooks.createHook({
        //初始化的时候被触发
        init(asyncId,type,superid,resource){
            // console.log("number>",number++)
            if(DATA.status){return}

            //现异步继承调用者的资源
            global.async[asyncId]=global.async[superid];
            DATA.group.push(asyncId);
            //替换池子
            // global.async[asyncId]=global.async[poolId];
        }
    }).enable(); // PromiseHooks 会被强制开启

    return {stop,data:DATA,$file}
}

//关闭异步全局变量
function stop(){
    try{
        this.data.status=true;
    }catch(e){
        console.log(async_global);
        console.log(e)
    }
    //删除临时的文件，如果有的话
    this.$file.forEach(obj=>{obj.delete()})
    //删除异步全局变量池
    this.data.group.forEach(value=>delete global.async[value]);
}
//初始化全局变量池
function init()
{
  if(global.async !== undefined){return global.async}
  //全局异步全局变量池
  global.async={};
  global.async.init=()=>{global.async[async_hooks.executionAsyncId()]={}};
  Object.defineProperties(global,{
    //异步全局变量池
    async_global:{get: function(){return global.async[async_hooks.executionAsyncId()];}},
    //删除异步全局变量池
    delete_async_global:{get: function(){delete global.async[async_hooks.executionAsyncId()]}},
  });
  //dd方法
  global.dd=(data)=>{async_global.req.statusCode=200;async_global.res.dd(data)};
  //echo方法
  global.echo=(data)=>{async_global.res.echo(data)};
  return global.async;
}